package sdb

import (
	"os"
	"fmt"
)

type Domain struct {
	Conn *Conn
	Name string
}

func (d *Domain) String() string {
	return fmt.Sprintf("SimpleDB %s at %s", d.Name, d.Conn.URL)
}

func (d *Domain) getResponse(action string, params map[string]string, xmlResp interface{}) (err os.Error) {
	if params == nil {
		params = make(map[string]string, 1)
	}
	params["DomainName"] = d.Name

	return d.Conn.getResponse(action, params, xmlResp)
}

func (c *Conn) ListDomains() (domains []string, err os.Error) {
	response := new(listDomainsResponse)
	if err = c.getResponse("ListDomains", nil, response); err != nil {
		return
	}

	domains = response.DomainNames
	for response.NextToken != "" {
		params := map[string]string{"NextToken": response.NextToken}
		if err = c.getResponse("ListDomains", params, response); err != nil {
			return nil, err
		}

		domains = append(domains, response.DomainNames...)
	}

	return domains, nil
}

func (c *Conn) CreateDomain(name string) (domain *Domain, err os.Error) {
	if err = c.getResponse("CreateDomain", map[string]string{"DomainName": name}, nil); err != nil {
		return
	}

	return &Domain{c, name}, nil
}

func (c *Conn) OpenDomain(name string) (domain *Domain, err os.Error) {
	return c.CreateDomain(name)
}

func (c *Conn) DeleteDomain(name string) os.Error {
	return c.getResponse("DeleteDomain", map[string]string{"DomainName": name}, nil)
}

func (d *Domain) Metadata() (md *DomainMetadata, err os.Error) {
	response := new(domainMetadataResponse)
	if err = d.getResponse("DomainMetadata", nil, response); err != nil {
		return
	}

	return response.DomainMetadataResult, nil
}
